package com.zry.pda.ui.activity

import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import android.util.Log
import com.zry.pda.R
import com.zry.pda.adapter.TraceCodeListAdapter
import com.zry.pda.animation.RecyclerViewUtilKt
import com.zry.pda.been.FlowCodeInfo
import com.zry.pda.been.LongAndShortCode
import com.zry.pda.been.ResultCode
import com.zry.pda.been.ResultFlowCode
import com.zry.pda.databinding.ActivityComplementInBoxSubmitBinding
import com.zry.pda.presenter.ComplementInBoxSubmitPresenter
import com.zry.pda.presenter.HttpServer
import com.zry.pda.retrofit.ShowUserView
import com.zry.pda.ui.base.BaseActivity
import com.zry.pda.utils.InputCodeFilter
import com.zry.pda.utils.KeyboardUtils
import com.zry.pda.utils.ToastUtil
import kotlinx.android.synthetic.main.activity_complement_in_box_submit.*
import kotlinx.android.synthetic.main.common_title.*

class ComplementInBoxSubmitActivity : BaseActivity(), ShowUserView {


    private var complementInBoxSubmitBinding: ActivityComplementInBoxSubmitBinding? = null
    private var complementInBoxSubmitPresenter: ComplementInBoxSubmitPresenter? = null
    private var traceCodeListAdapter: TraceCodeListAdapter? = null
    var longAndShortCodeList: MutableList<LongAndShortCode>? = null
    var title = ""
    var flowCodeInfo: FlowCodeInfo? = null
    var parentCode: String? = null
    override fun getLayoutId(): Int {
        return R.layout.activity_complement_in_box_submit
    }

    override fun initData() {
        title = intent.getStringExtra("title")
        parentCode = intent.getStringExtra("parentCode")
        flowCodeInfo = intent.getSerializableExtra("flowCodeInfo") as FlowCodeInfo
        titleCenterText.text = title
        commonLeftLinearLayout.setOnClickListener { finish() }

        when (title) {
            "补码入箱" -> {
                inboxSubmitCodeBtn.setText(R.string.complementInBox)
            }

            "拆码出箱" -> {
                inboxSubmitCodeBtn.setText(R.string.dismantlingBox)
            }
        }

        complementInBoxSubmitBinding = viewDataBinding as ActivityComplementInBoxSubmitBinding
        complementInBoxSubmitPresenter = ComplementInBoxSubmitPresenter(this)
        complementInBoxSubmitBinding?.handlerClick = complementInBoxSubmitPresenter


        longAndShortCodeList = mutableListOf()
        initView()
    }

    private fun initView() {
        currentQuantityTV.text = flowCodeInfo!!.CodeNum
        when (title) {
            "补码入箱" -> {
                val codeNum = getNumber(flowCodeInfo!!.Radio).toInt() - flowCodeInfo!!.CodeNum.toInt()
                complementaryQuantityTV.text = codeNum.toString()
            }
            "拆码出箱" -> {
                complementaryQuantityLinear.text = "可拆数量"
                complementaryQuantityTV.text = flowCodeInfo!!.CodeNum
            }
        }

        initRecycler()

        initEditCode()
    }

    private fun initEditCode() {
        inBoxSubmitET.filters = arrayOf<InputFilter>(InputCodeFilter())
        inBoxSubmitET.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) = Unit
            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) = Unit
            override fun afterTextChanged(p0: Editable?) {
                val codeString = inBoxSubmitET.text.toString().trim()
                Log.e("codeString", codeString)

                when (title) {
                    "补码入箱" -> {
                        if (longAndShortCodeList!!.size <= getNumber(flowCodeInfo!!.Radio).toInt() - flowCodeInfo!!.CodeNum.toInt()) {
                            setCode(codeString)
                        }
//                        else {
//                            return ToastUtil.toast(this@ComplementInBoxSubmitActivity, "已达到最大可补码数量")
//
//                        }
                    }
                    "拆码出箱" -> {
                        if (longAndShortCodeList!!.size <= flowCodeInfo!!.CodeNum.toInt()) {
                            setCode(codeString)
                        }
//                        else {
//                            return ToastUtil.toast(this@ComplementInBoxSubmitActivity, "已达到最大可拆码数量")
//                        }
                    }
                }
            }
        })
    }

    fun setCode(codeString: String) {
        if (codeString != "") {
            setRequestFocusFalse()
            getFlowCodeInfo(codeString)
        }
    }

    private fun getFlowCodeInfo(codeString: String) {
        when (flowCodeInfo!!.Level) {
            "2" -> {
                when (title) {
                    "补码入箱" -> {
                        //追溯码
                        HttpServer(this).getLongTraceCode(codeString, flowCodeInfo!!.ProductID, "4", parentCode!!, this)
                    }
                    "拆码出箱" -> {
                        //追溯码
                        HttpServer(this).getLongTraceCode(codeString, flowCodeInfo!!.ProductID, "5", parentCode!!, this)
                    }
                }
            }
            "3" -> {
                when (title) {
                    "补码入箱" -> {
                        //流通码
                        HttpServer(this).getLongCirculationCode(codeString, flowCodeInfo!!.ProductID, "4", "", parentCode!!, this)
                    }
                    "拆码出箱" -> {
                        //流通码
                        HttpServer(this).getLongCirculationCode(codeString, flowCodeInfo!!.ProductID, "5", "", parentCode!!, this)
                    }
                }
            }
        }
    }


    override fun toMainActivity(what: Int, data: Any) {
        when (what) {
            5 -> {
                val resultCode: ResultCode = data as ResultCode
                if (resultCode.state == "1") {
                    val longAndShortCode = LongAndShortCode(resultCode.CodeID, resultCode.shortCode)
                    notifyAdapter(longAndShortCode)
                } else {
                    toast(resultCode.Message)
                    inBoxSubmitET.setText("")
                    getEditFocusTrue()
                    KeyboardUtils().hideKeyboard(this)
                }
            }
            6 -> {
                val resultCode: ResultFlowCode = data as ResultFlowCode
                if (resultCode.state == "1") {
                    val longAndShortCode = LongAndShortCode(resultCode.Code, resultCode.shortCode)
                    notifyAdapter(longAndShortCode)
                } else {
                    toast(resultCode.Message)
                    inBoxSubmitET.setText("")
                    getEditFocusTrue()
                    KeyboardUtils().hideKeyboard(this)
                }
            }
        }
    }

    private fun notifyAdapter(longAndShortCode: LongAndShortCode) {
        when {
            longAndShortCodeList!!.contains(longAndShortCode) -> toast("此追溯码已存在列表中")
            else -> {
                longAndShortCodeList!!.add(longAndShortCode)
                traceCodeListAdapter?.notifyDataSetChanged()
            }
        }
        inBoxSubmitET.setText("")
        getEditFocusTrue()
        KeyboardUtils().hideKeyboard(this)
    }


    private fun initRecycler() {
        val recyclerViewUtilKt = RecyclerViewUtilKt(this, inBoxSubmitStorageRecycler)
        recyclerViewUtilKt.initRecyclerView()
        traceCodeListAdapter = TraceCodeListAdapter(R.layout.trace_code_item, longAndShortCodeList!!)
        recyclerViewUtilKt.setAdapter(traceCodeListAdapter!!)
        traceCodeListAdapter!!.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.traceCodeDeleteImg -> {
                    longAndShortCodeList!!.removeAt(position)
                    traceCodeListAdapter?.notifyDataSetChanged()
                }
            }
        }
    }

    private fun getNumber(sourceStr: String): String {
        val sourceStrArray = sourceStr.split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
        return sourceStrArray[0]
    }


    private fun getEditFocusTrue() {
        inBoxSubmitET.setText("")
        //获取焦点
        inBoxSubmitET.isFocusable = true
        inBoxSubmitET.isFocusableInTouchMode = true
        //显示光标
        inBoxSubmitET.requestFocus()
        inBoxSubmitET.isCursorVisible = true
    }


    private fun setRequestFocusFalse() {
        //取消焦点
        inBoxSubmitET.isFocusable = false
        inBoxSubmitET.isFocusableInTouchMode = false
        //隐藏光标
        inBoxSubmitET.isCursorVisible = false
    }
}
